package com.fucking.great.boot;

import cn.hutool.json.JSONObject;
import com.fucking.great.context.TxnContext;
import com.fucking.great.context.common.DynGraphqlResolver;
import com.fucking.great.servlert.HadnlerServlet;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class HadnlerController {

    @RequestMapping("/api/{appid}/{system}/**")
    public void api(@PathVariable("appid") String appid, @PathVariable("system") String system, HttpServletRequest request, HttpServletResponse response) throws IOException {
        appid = appid.trim();
        system = system.trim();
        // 初始化
        TxnContext txnContext = HadnlerServlet.initContextByRequest(request);
        // 设置appid 和 systemName 参数
        txnContext.setAppid(appid);
        txnContext.setSystemName(system);
        //  spring boot @PathVariable 传递带有反斜杠的参数“/”
        // 获得处理路径
        final String path =
                request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        final String bestMatchingPattern =
                request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        //
        String contextPath = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);
        //设置处理的路径
        txnContext.setPath(contextPath);
        //调用服务处理内容
        HadnlerServlet.handlerContext(response,txnContext);
    }

    @RequestMapping("/api/{appid}/{system}/graph")
    public JSONObject graph(@PathVariable("appid") String appid, @PathVariable("system") String system, HttpServletRequest request, HttpServletResponse response) throws Exception {
            //
            DynGraphqlResolver dynGraphqlResolver = HadnlerServlet.initDynGraphqlByRequest(request);
            // set内容
            appid = appid.trim();
            system = system.trim();
            TxnContext txnContext = TxnContext.getContext();
            txnContext.setAppid(appid);
            txnContext.setSystemName(system);
            //
            JSONObject run = dynGraphqlResolver.run();
            return run;
    }

}